package com.tiance.common;

import com.tiance.enums.ErrorCodeEnum;
import com.tiance.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 *
 * @author 雷霆
 * @version 1.0.0
 * @date$ 2019/1/30
 *
 * Description：
 *
 * Modification History:
 *
 */
public class ServiceContextHolder {

    private static Logger logger = LoggerFactory.getLogger(ServiceContextHolder.class);

    private static ThreadLocal<ServiceContext> tl     = new ThreadLocal<ServiceContext>();

    public static ServiceContext get() {
        if (tl.get() == null) {
            logger.error("service context not exist");
            throw new BusinessException(ErrorCodeEnum.SYSTEM_ERROR);
        }
        return tl.get();
    }

    public static void set(ServiceContext sc) {
        if (tl.get() != null) {
            logger.error("service context not null");
            tl.remove();
        }
        tl.set(sc);
    }

    public static void cleanUp() {
        try{
            if (tl.get() != null) {
                tl.remove();
            } 
        }catch(Exception e){
            logger.error(e.getMessage(),e);
        }
    }
}
